﻿Imports System.Text
Imports System.IO
Imports System.Globalization

Namespace VsSpeakerCompanion
	''' <summary>
	''' Very simple logger used for dumping unhandled exceptions to disk
	''' </summary>
	Friend Class Logger
		' Full path to log file
		Private Shared LogFile As String

		Shared Sub New()
			' The path to the file will be the path from where Demo Dashboard was loaded
			' This is the file you may want to look at for hints when dealing with potential bugs, etc.
			LogFile = Path.Combine(Path.GetDirectoryName(GetType(Logger).Assembly.Location), "log.txt")
		End Sub

		''' <summary>
		''' Logs a message
		''' </summary>
		''' <param name="message">text message to log</param>
		''' <param name="args">variable list of arguments to log</param>
		Friend Shared Sub Log(ByVal message As String, ParamArray ByVal args() As String)
			Try
				' Make sure we have a file to write to
				EnsureLogFile()
				' TODO: Although the logged info should be minimal not reciclying the log file could be an issue sooner than later
				File.AppendAllText(LogFile, GetMessage(message, args))
			Catch
			End Try
		End Sub


		''' <summary>
		''' Used to format a message with some common formatting before logging it
		''' </summary>
		''' <param name="message"></param>
		''' <param name="args"></param>
		''' <returns></returns>
		Private Shared Function GetMessage(ByVal message As String, ParamArray ByVal args() As Object) As String
            Dim result = message

			If args IsNot Nothing Then
				result = String.Format(CultureInfo.CurrentUICulture, message, args)
			End If

			Return DateTime.Now.ToString() & ": " & result & Environment.NewLine
		End Function

		''' <summary>
		''' Logs an exception and its details to disk
		''' </summary>
		''' <param name="ex"></param>
		Friend Shared Sub Log(ByVal ex As Exception)
			Log(ex.GetType().FullName & ": " & ex.Message)
			If ex.InnerException IsNot Nothing Then
				Log(ex.InnerException)
			End If
		End Sub

		''' <summary>
		''' Make sure we always have a log file to write to
		''' </summary>
		Private Shared Sub EnsureLogFile()
			If File.Exists(LogFile) Then
                If (File.GetAttributes(LogFile) And FileAttributes.ReadOnly) <> 0 Then
                    File.SetAttributes(LogFile, FileAttributes.Normal)
                End If
			Else
                Dim myPath = Path.GetDirectoryName(LogFile)

                If Not Directory.Exists(myPath) Then
                    Directory.CreateDirectory(myPath)
                End If
			End If
		End Sub
	End Class
End Namespace
